import { createStore } from 'vuex'
import homeModule from './modules/home'
import courseModule from './modules/course'
import communityModule from './modules/community'
import userModule from './modules/user'
import { getUserInfo } from '@/api/login.js'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { logout } from '@/api/login'

const store = createStore({
  state: {
    token: getToken(),
    userInfo: null,
    permissions: [],
    roles: []
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      if (token) {
        setToken(token)
      } else {
        removeToken()
      }
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    CLEAR_USER_INFO: (state) => {
      state.userInfo = null
    }
  },
  actions: {
    // 登录成功
    loginSuccess({ commit }, token) {
      commit('SET_TOKEN', token)
    },
    // 获取用户信息
    getUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        // 这里调用获取用户信息的API
        // 成功后提交用户信息到store
        try {
          const res = {/* 模拟响应数据 */}
          const userInfo = res.user || {}
          commit('SET_USER_INFO', userInfo)
          commit('SET_PERMISSIONS', userInfo.permissions)
          commit('SET_ROLES', userInfo.roles)
          resolve(userInfo)
        } catch (error) {
          reject(error)
        }
      })
    },
    // 设置权限
    setPermissions({ commit }, permissions) {
      commit('SET_PERMISSIONS', permissions)
    },
    // 设置角色
    setRoles({ commit }, roles) {
      commit('SET_ROLES', roles)
    },
    // 登出
    logout({ commit }) {
      return new Promise((resolve, reject) => {
        try {
          logout().then(() => {
            commit('SET_TOKEN', '')
            commit('CLEAR_USER_INFO')
            commit('SET_PERMISSIONS', [])
            commit('SET_ROLES', [])
            resolve()
          }).catch(error => {
            reject(error)
          })
        } catch (error) {
          // 即使API调用失败，也清除本地存储
          commit('SET_TOKEN', '')
          commit('CLEAR_USER_INFO')
          commit('SET_PERMISSIONS', [])
          commit('SET_ROLES', [])
          resolve()
        }
      })
    }
  },
  getters: {
    token: state => state.token,
    userInfo: state => state.userInfo,
    permissions: state => state.permissions,
    roles: state => state.roles,
    isAuthenticated: state => !!state.token
  },
  modules: {
    home: homeModule,
    course: courseModule,
    community: communityModule,
    user: userModule
  }
})

export default store
